<!-- 模板 -->
<template>
  <div class="params">
    <!-- 1、导航 -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>参数管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数操作</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、卡片 -->
    <el-card>
      <!-- 2-1 警告条 -->
      <el-row>
        <el-col>
          <el-alert
            title="只能对三级分类的信息进行操作"
            type="info"
            show-icon
            :closable="false"
          />
        </el-col>
      </el-row>
      <!-- 2-2 选择分类 -->
      <el-row class="cate-row">
        <el-col :span="8">
          <div style="width: 120px;padding-right:10px">请选择分类:</div>
          <el-cascader
            style="width: 100%"
            v-model="cates"
            :options="options"
            :props="props"
            :clearable="true"
            size="large"
            placeholder="请选择分类"
            @change="handleCascaderChange"
          />
        </el-col>
      </el-row>
      <!-- 2-3 标签页 -->
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="getCatesAttr">
        <el-tab-pane label="商品参数" name="many">
          <div>
            <el-button type="primary" :disabled="disabled" @click="showAddMany"
              >添加商品参数</el-button
            >
          </div>
          <el-table
            :data="manyAttrList.value"
            border
            stripe
            style="width: 100%"
            :header-cell-style="header_cell_style"
            row-key="attr_id"
          >
            <el-table-column
              type="expand"
              label="展开"
              width="80"
              align="center"
            >
              <template #default="props">
                <div class="tag-list">
                  <el-tag
                    v-for="tag in props.row.attr_vals"
                    :key="tag"
                    class="mx-1"
                    closable
                    type="success"
                    size="large"
                    :disable-transitions="false"
                    @close="handleClose(tag, props.row)"
                    effect="dark"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-show="props.row.inputVisible"
                    :ref="'inputRef' + props.row.attr_id"
                    v-model="props.row.inputValue"
                    :class="['ml-1', 'w-20', 'inputRef' + props.row.attr_id]"
                    size="large"
                    @keyup.enter="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  />
                  <el-button
                    v-show="!props.row.inputVisible"
                    class="button-new-tag ml-1"
                    size="large"
                    @click="
                      showInput(props.row, 'inputRef' + props.row.attr_id)
                    "
                  >
                    + New Tag
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            />
            <el-table-column
              prop="attr_name"
              label="参数名称"
              width="280"
              align="center"
            />
            <el-table-column label="操作" align="center">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  :icon="EditPen"
                  @click="showUpdateDialog(row)"
                  >修改</el-button
                >
                <el-button type="danger" :icon="Delete" @click="deleteAttr(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="only">
          <div>
            <el-button type="primary" :disabled="disabled" @click="showAddMany"
              >添加商品属性</el-button
            >
          </div>
          <el-table
            :data="onlyAttrList.value"
            border
            stripe
            style="width: 100%"
            :header-cell-style="header_cell_style"
            row-key="attr_id"
          >
            <el-table-column
              type="expand"
              label="展开"
              width="80"
              align="center"
            >
              <template #default="props">
                <div class="tag-list">
                  <el-tag
                    v-for="tag in props.row.attr_vals"
                    :key="tag"
                    class="mx-1"
                    closable
                    type="success"
                    :disable-transitions="false"
                    @close="handleClose(tag, props.row)"
                    effect="dark"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-show="props.row.inputVisible"
                    :ref="'inputRef' + props.row.attr_id"
                    v-model="props.row.inputValue"
                    :class="['ml-1', 'w-20', 'inputRef' + props.row.attr_id]"
                    size="small"
                    @keyup.enter="handleInputConfirm(props.row)"
                    @blur="handleInputConfirm(props.row)"
                  />
                  <el-button
                    v-show="!props.row.inputVisible"
                    class="button-new-tag ml-1"
                    size="small"
                    @click="
                      showInput(props.row, 'inputRef' + props.row.attr_id)
                    "
                  >
                    + New Tag
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            />
            <el-table-column
              prop="attr_name"
              label="参数名称"
              width="280"
              align="center"
            />
            <el-table-column label="操作" align="center">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  :icon="EditPen"
                  @click="showUpdateDialog(row)"
                  >修改</el-button
                >
                <el-button type="danger" :icon="Delete" @click="deleteAttr(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 3、添加参数对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加参数"
      width="50%"
      @close="reset(addFormRef)"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="addForm.attr_name" size="large" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitAdd(addFormRef)">添加</el-button>
          <el-button type="primary" @click="addDialogVisible = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 4、修改参数对话框 -->
    <el-dialog
      v-model="updateDialogVisible"
      title="修改参数"
      width="50%"
      @close="reset(updateFormRef)"
    >
      <el-form
        ref="updateFormRef"
        :model="updateForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="updateForm.attr_name" size="large" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitUpdate(updateFormRef)">修改</el-button>
          <el-button type="primary" @click="updateDialogVisible = false"
            >取消</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
/*--------------------------------------引入资源-----------------------------------------*/
import {
  ref,
  onMounted,
  computed,
  nextTick,
  getCurrentInstance,
  reactive,
} from "vue";
import request from "../utils/request.js";
import { useRouter } from "vue-router";
import { ArrowRight, EditPen, Delete } from "@element-plus/icons-vue";
import { error, success, confirm, info } from "@/utils/message";
/*--------------------------------------定义变量-----------------------------------------*/
let updateFormRef = ref(),
  updateForm = reactive({
    attr_id: 0,
    attr_name: "",
    attr_vals: "",
  }),
  rules = reactive({
    attr_name: [
      { required: true, message: "请输入分类参数名称", trigger: "blur" },
      {
        min: 2,
        max: 15,
        message: "分类参数名称长度 2-15字符",
        trigger: "blur",
      },
    ],
  }),
  addFormRef = ref(""),
  addForm = reactive({ attr_name: "" }),
  ctx = getCurrentInstance(),
  activeName = ref("many"),
  inputRef = ref(""),
  cates = ref([]),
  disabled = computed(() => {
    if (!cates.value) {
      return true;
    }
    return cates.value.length === 0;
  }),
  props = {
    expandTrigger: "hover",
    label: "cat_name",
    value: "cat_id",
    children: "children",
  },
  options = ref([]),
  manyAttrList = reactive({ value: [] }),
  onlyAttrList = reactive({ value: [] }),
  header_cell_style = {
    backgroundColor: "#00A0FF",
    color: "#ffffff",
    textAlign: "center",
  },
  addDialogVisible = ref(false),
  updateDialogVisible = ref(false);
/*---------------------定义函数---------------------*/
// 点击删除参数
function deleteAttr(attr) {
  confirm("确定要删除吗？", "删除参数", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    type: "warning",
  })
    .then(async () => {
      let option = {
        url: `categories/${cates.value[2]}/attributes/${attr.attr_id}`,
        type: "delete",
      };
      try {
        let { data: res } = await request(option);
        if (res.meta.status !== 200) {
          return error(res.meta.msg);
        }
        success(res.meta.msg);
        getCatesAttr();
      } catch (error) {
        console.log(error);
      }
    })
    .catch(() => {
      info("您取消了删除");
    });
}
// 点击显示修改对话框
function showUpdateDialog(attr) {
  updateForm.attr_id = attr.attr_id;
  updateForm.attr_name = attr.attr_name;
  updateForm.attr_vals = attr.attr_vals.join(",");
  updateDialogVisible.value = true;
}
// 执行修改参数过程
async function updateAttr() {
  let option = {
    url: `categories/${cates.value[2]}/attributes/${updateForm.attr_id}`,
    type: "put",
    data: {
      attr_name: updateForm.attr_name,
      attr_sel: activeName.value,
      attr_vals: updateForm.attr_vals,
    },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    updateDialogVisible.value = false;
    getCatesAttr();
  } catch (error) {
    console.log(error);
  }
}
// 提交修改请求
function submitUpdate(form) {
  form.validate((v) => {
    v && updateAttr();
  });
}
// 执行添加参数操作
async function addAttr() {
  let option = {
    url: `categories/${cates.value[2]}/attributes`,
    type: "post",
    data: { attr_name: addForm.attr_name, attr_sel: activeName.value },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 201) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    addDialogVisible.value = false;
    getCatesAttr();
  } catch (error) {
    console.log(error);
  }
}
// 提交添加操作
function submitAdd(form) {
  form.validate((v) => {
    v && addAttr();
  });
}
// 重置表单
function reset(form) {
  form.resetFields();
}
// 点击显示添加动态参数对话框
function showAddMany() {
  addDialogVisible.value = true;
}
// 点击button显示input
function showInput(row, str) {
  // r是input框
  let r = ctx.refs[str];
  row.inputVisible = true;
  nextTick(() => {
    r.focus();
  });
}
// 点击关闭tag时执行的操作
async function handleClose(tag, attr) {
  let vals = attr.attr_vals,
    index = vals.findIndex((v) => v === tag);
  vals.splice(index, 1);
  let options = {
    url: `categories/${cates.value[2]}/attributes/${attr.attr_id}`,
    type: "put",
    data: {
      attr_name: attr.attr_name,
      attr_sel: activeName.value,
      attr_vals: vals.join(","),
    },
  };
  try {
    let { data: res } = await request(options);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
  } catch (error) {
    console.log(error);
  }
}
// input框失去焦点或回车时执行的操作
async function handleInputConfirm(attr) {
  let vals = attr.attr_vals,
    value = attr.inputValue;
  if (!value) {
    return;
  }
  let index = vals.findIndex((v) => v === value);
  if (index !== -1) {
    return error("动态属性不能重复");
  }
  vals.push(value);
  // 修改当前商品分类的动态属性值
  let options = {
    url: `categories/${cates.value[2]}/attributes/${attr.attr_id}`,
    type: "put",
    data: {
      attr_name: attr.attr_name,
      attr_sel: activeName.value,
      attr_vals: vals.join(","),
    },
  };
  try {
    let { data: res } = await request(options);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    success(res.meta.msg);
    attr.inputVisible = false;
    attr.inputValue = "";
  } catch (error) {
    console.log(error);
  }
}
// 分类cascader发生变化时
function handleCascaderChange() {
  manyAttrList.value = [];
  onlyAttrList.value = [];
  getCatesAttr();
}
// tabs标签页点击操作，获得指定分类的参数
async function getCatesAttr() {
  if (!cates.value) {
    return;
  }
  let id = cates.value[2];
  if (!id) {
    return;
  }
  let option = {
    url: "categories/" + id + "/attributes",
    type: "get",
    data: { sel: activeName.value },
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    let arr = JSON.parse(JSON.stringify(res.data));
    for (let item of arr) {
      let vals = item.attr_vals;
      item.inputValue = "";
      item.inputVisible = false;
      if (!vals) {
        item.attr_vals = [];
      } else {
        item.attr_vals = vals.split(",");
      }
    }
    if (activeName.value === "many") {
      manyAttrList.value = arr;
    } else {
      onlyAttrList.value = arr;
    }
    console.log(arr);
  } catch (error) {
    console.log(error);
  }
}
// 请求级联选择器分类列表
async function getCatesList() {
  let option = {
    url: "categories",
    type: "get",
  };
  try {
    let { data: res } = await request(option);
    if (res.meta.status !== 200) {
      return error(res.meta.msg);
    }
    options.value = res.data;
  } catch (error) {
    console.log(error);
  }
}
onMounted(() => {
  getCatesList();
  getCatesAttr();
});
</script>
<style lang="scss" scoped>
.el-card {
  margin: 20px 0;
  font-size: 14px;
}
.el-table {
  margin: 10px 0;
}
.el-alert {
  background-color: darkblue;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  :deep(.el-alert__content) {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  &:hover {
    background-color: rgb(0, 0, 92);
    cursor: pointer;
  }
}
.cate-row {
  display: flex;
  padding: 15px 0;
  .el-col {
    display: flex;
    align-items: center;
  }
}
.tag-list {
  display: flex;
  .el-tag {
    margin-right: 10px;
  }
  .el-input {
    width: 100px;
  }
}
</style>